package com.ruicar.afs.cloud.product.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.ProductDiscountPlanCondition;
import com.ruicar.afs.cloud.product.condition.ProductDiscountSubsidyCondition;
import com.ruicar.afs.cloud.product.entity.ProductDiscountPlan;
import com.ruicar.afs.cloud.product.entity.ProductDiscountSubsidy;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.enums.StatusType;
import com.ruicar.afs.cloud.product.service.ProductDiscountConfigService;
import com.ruicar.afs.cloud.product.service.ProductDiscountPlanService;
import com.ruicar.afs.cloud.product.vo.ExtrasInfoVo;
import com.ruicar.afs.cloud.product.vo.ProductDiscountSubsidyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xudongdong
 * @date 2020-05-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("/productDiscountConfig")
@Api(value = "productDiscountConfig", description = "产品贴息配置")
public class ProductDiscountConfigController {

    private final ProductDiscountPlanService productDiscountPlanService;
    private final ProductDiscountConfigService productDiscountConfigService;
    private final AfsSequenceGenerator afsSequenceGenerator;

    @PostMapping(value = "/getDiscountConfigData")
    @ApiOperation(value = "多条件分页获取产品补贴方信息")
    public IResponse<IPage<ProductDiscountSubsidy>> getDiscountConfigData(@RequestBody ProductDiscountSubsidyCondition config) {
        Page page = new Page(config.getPageNumber(), config.getPageSize());
        IPage<List<ProductDiscountSubsidyVo>> list = productDiscountConfigService.getDiscountConfigData(page, config);
        return IResponse.success(list);
    }

    @PostMapping(value = "/getSelectDiscountRuleData")
    @ApiOperation(value = "获取贴息规则信息")
    public IResponse<IPage<ExtrasInfoVo>> getSelectDiscountRuleData() {
        List<ExtrasInfoVo> list = productDiscountConfigService.getSelectDiscountRuleData();
        return IResponse.success(list);
    }

    @PostMapping(value = "/saveOrUpdateConfig")
    @ApiOperation(value = "保存贴息方案信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<ProductDiscountPlan> saveOrUpdateConfig(@ModelAttribute ProductDiscountPlan productDiscountPlan) {
        if (productDiscountPlan.getId() == null) {
            productDiscountPlan.setStatus(AfsEnumUtil.key(StatusEnum.NO));
            productDiscountPlanService.save(productDiscountPlan);
        } else {
            productDiscountPlanService.updateById(productDiscountPlan);
        }
        return IResponse.success(productDiscountPlan);
    }

    @PostMapping(value = "/saveSubsidy")
    @ApiOperation(value = "保存贴息补贴信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> saveSubsidy(@ModelAttribute ProductDiscountSubsidyCondition config) {
        ProductDiscountPlan productDiscountPlan = productDiscountPlanService.getById(config.getDiscountPlanId());
        ProductDiscountSubsidy discountSubsidy = productDiscountConfigService.getOne(Wrappers.<ProductDiscountSubsidy>query().lambda()
                .eq(ProductDiscountSubsidy::getDiscountPlanId, config.getDiscountPlanId()).orderByDesc(ProductDiscountSubsidy::getDiscountSerialNumber), false);
        int serialNumber = 1;
        if (discountSubsidy != null) {
            serialNumber = discountSubsidy.getDiscountSerialNumber() + 1;
        }
        if (AfsEnumUtil.key(StatusEnum.NO).equals(config.getSingleSelect())) {
            config.setDiscountRulePlanId(Long.valueOf(config.getSubsidy()));
        } else {
            config.setSingleSelect(AfsEnumUtil.key(StatusEnum.YES));
            config.setSubsidyMoney(new BigDecimal(config.getSubsidy()));
        }
        config.setDiscountSerialNumber(serialNumber);
        productDiscountConfigService.save(config);
        return IResponse.success("操作成功");
    }

    @PostMapping("/upConfig")
    @ApiOperation(value = "上移项目")
    @SysLog("上移项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> upConfig(@ModelAttribute ProductDiscountSubsidyCondition config) {
        ProductDiscountSubsidy discountSubsidy = productDiscountConfigService.getById(config.getId());
        Boolean flag = productDiscountConfigService.update(Wrappers.<ProductDiscountSubsidy>update().lambda().set(ProductDiscountSubsidy::getDiscountSerialNumber, discountSubsidy.getDiscountSerialNumber())
                .eq(ProductDiscountSubsidy::getDiscountSerialNumber, discountSubsidy.getDiscountSerialNumber() - 1)
                .eq(ProductDiscountSubsidy::getDiscountPlanId, discountSubsidy.getDiscountPlanId())
        );
        if (!flag) {
            return IResponse.fail("不可上移");
        }
        discountSubsidy.setDiscountSerialNumber(discountSubsidy.getDiscountSerialNumber() - 1);
        productDiscountConfigService.updateById(discountSubsidy);
        return new IResponse<Boolean>().setData(true).setMsg("上移项目成功");
    }

    @PostMapping("/downConfig")
    @ApiOperation(value = "下移项目")
    @SysLog("下移项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> downConfig(@ModelAttribute ProductDiscountSubsidyCondition config) {
        ProductDiscountSubsidy discountSubsidy = productDiscountConfigService.getById(config.getId());
        Boolean flag = productDiscountConfigService.update(Wrappers.<ProductDiscountSubsidy>update().lambda().set(ProductDiscountSubsidy::getDiscountSerialNumber, discountSubsidy.getDiscountSerialNumber())
                .eq(ProductDiscountSubsidy::getDiscountSerialNumber, discountSubsidy.getDiscountSerialNumber() + 1)
                .eq(ProductDiscountSubsidy::getDiscountPlanId, discountSubsidy.getDiscountPlanId())
        );
        if (!flag) {
            return IResponse.fail("不可下移");
        }
        discountSubsidy.setDiscountSerialNumber(discountSubsidy.getDiscountSerialNumber() + 1);
        productDiscountConfigService.updateById(discountSubsidy);
        return new IResponse<Boolean>().setData(true).setMsg("下移项目成功");
    }

    @RequestMapping(value = "/delById/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除")
    @Transactional
    @SysLog("删除贴息补贴信息")
    public IResponse<Boolean> delById(@PathVariable String id) {
        productDiscountConfigService.removeById(id);
        return new IResponse<Boolean>().setMsg("删除数据成功");
    }

    @PostMapping(value = "/saveOrUpdateConfigByType")
    @ApiOperation(value = "保存贴息方案信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<ProductDiscountPlan> saveOrUpdateConfigByType(@RequestBody ProductDiscountPlanCondition condition) {
        //保存或修改贴息方案信息
        ProductDiscountPlan productDiscountPlan = condition.getProductDiscountPlan();
        if(productDiscountPlan.getId()!=null){
            //查询是否有相同编号的方案
            ProductDiscountPlan productDiscountPlanTwo = productDiscountPlanService.getOne(Wrappers.<ProductDiscountPlan>query().lambda()
                            .eq(ProductDiscountPlan::getDiscountPlanName, productDiscountPlan.getDiscountPlanName())
                            .notIn(ProductDiscountPlan::getId, productDiscountPlan.getId())
                    , false
            );
            if (productDiscountPlanTwo != null) {
                return IResponse.fail("名称重复，请重新填写方案名称！");
            }
        }else{
            //查询是否有相同编号的方案
            ProductDiscountPlan productDiscountPlanTwo = productDiscountPlanService.getOne(Wrappers.<ProductDiscountPlan>query().lambda()
                            .eq(ProductDiscountPlan::getDiscountPlanName, productDiscountPlan.getDiscountPlanName())
                    , false
            );
            if (productDiscountPlanTwo != null) {
                return IResponse.fail("名称重复，请重新填写方案名称！");
            }
        }

        //获取编号
        String planNo = condition.getDiscountNo();
        if(StringUtils.isEmpty(planNo)){
            Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_TXFA), StatusType.PRODUCT_NUM_TXFA.toString());
            planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_TXFA) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
            productDiscountPlan.setDiscountNo(planNo);
        }
        //保存方案
        productDiscountPlan.setStatus(AfsEnumUtil.key(StatusType.INVALID));
        productDiscountPlanService.saveOrUpdate(productDiscountPlan);
        //保存或修改补贴信息
        List ids = new ArrayList();
        List<ProductDiscountSubsidy> productDiscountSubsidyList = condition.getProductDiscountSubsidyList();
        for (int i = 0; i < productDiscountSubsidyList.size(); i++) {
            //保存或修改补贴信息
            ProductDiscountSubsidy productDiscountSubsidy = productDiscountSubsidyList.get(i);
            productDiscountSubsidy.setDiscountSerialNumber(i);//默认排序
            productDiscountSubsidy.setDiscountPlanId(productDiscountPlan.getId());
            productDiscountSubsidy.setId(null);
            productDiscountConfigService.saveOrUpdate(productDiscountSubsidy);
            //保存好的ID进行存储
            ids.add(productDiscountSubsidy.getId());
        }
        //删除补贴信息
        productDiscountConfigService.remove(Wrappers.<ProductDiscountSubsidy>update().lambda()
                .notIn(ProductDiscountSubsidy::getId, ids)
                .eq(ProductDiscountSubsidy::getDiscountPlanId, productDiscountPlan.getId())
        );
        return IResponse.success("保存成功！");
    }


    @PostMapping(value = "/getDiscountConfigDataByPlanID/{id}")
    @ApiOperation(value = "贴息方案列表查询")
    public IResponse getDiscountConfigDataByPlanID(@PathVariable Long id) {
        List<ProductDiscountSubsidy> list = productDiscountConfigService.list(Wrappers.<ProductDiscountSubsidy>query().lambda()
                .eq(ProductDiscountSubsidy::getDiscountPlanId, id)
                .orderByAsc(ProductDiscountSubsidy::getDiscountSerialNumber)
        );
        return new IResponse().setData(list);
    }

}
